const data = {
  xAxis: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
  array: [100, 200, 500, 450, 300, 720, 180],
  title: "前端周销售额(万)",
};

const ns = "http://www.w3.org/2000/svg";
const svg = document.querySelector("#svg");

let max = data.array.reduce((e1, e2) => Math.max(e1, e2));

//最大值取整，确保图形上方留有一定
max = ceil(max);
const ratio = max / 100;

//设置viewBox， 上下左右各留100留白
svg.setAttribute("viewBox", `0 0 ${max + 200} ${max + 200}`);

//设置标题
const title = document.createElementNS(ns, "text");
title.setAttribute("x", 100);
title.setAttribute("y", 40);
title.setAttribute("font-size", 3 * ratio);
title.innerHTML = data.title;
svg.appendChild(title);

//绘制横轴，规定绘制5条线4个间隔， 计算每个的间距，上下还有
//绘制y轴数字
const ySpace = max / 4;
let d = "";
for (let i = 0; i < 5; i++) {
  d += `M100 ${max + 100 - i * ySpace}H${max + 100}`;
  const text = document.createElementNS(ns, "text");
  text.setAttribute("x", 50);
  text.setAttribute("y", max + 100 - i * ySpace);
  text.setAttribute("font-size", 2 * ratio);
  text.classList.add("y-text");
  text.innerHTML = i * ySpace;
  svg.appendChild(text);
}
const coordPath = document.createElementNS(ns, "path");
coordPath.setAttribute("d", d);
coordPath.classList.add("line");
svg.appendChild(coordPath);

//绘制x轴小竖线，7天，分成7份 , 8个线
const xSpace = max / 7;
d = "";
for (let i = 0; i < 8; i++) {
  d += `M${100 + i * xSpace} ${max + 100}V${max + 110}`;
}
const segmentPath = document.createElementNS(ns, "path");
segmentPath.setAttribute("d", d);
segmentPath.classList.add("line");
svg.appendChild(segmentPath);

//绘制x轴文字
const textSpace = xSpace / 3;
data.xAxis.forEach((e, i) => {
  const text = document.createElementNS(ns, "text");
  text.setAttribute("x", 100 + i * xSpace + textSpace);
  text.setAttribute("y", max + 100 + 20);
  text.setAttribute("font-size", 2 * ratio);
  text.innerHTML = e;
  svg.appendChild(text);
});

//绘制柱形
const pillarSpace = xSpace / 4;
data.array.forEach((v, i) => {
  const rect = document.createElementNS(ns, "rect");
  rect.setAttribute("x", 100 + i * xSpace + pillarSpace);
  rect.setAttribute("y", max + 100 - v);
  rect.setAttribute("width", pillarSpace * 2);
  rect.setAttribute("height", v);
  rect.classList.add("pillar");
  svg.appendChild(rect);
});
